//
//  ShopsSearchViewController.m
//  何五路
//
//  Created by _ADY on 15/7/8.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "ShopsSearchViewController.h"

@interface ShopsSearchViewController ()

@end
#define geHight 50
#define sizeHight (screenMySize.size.width-30)/2
@implementation ShopsSearchViewController
@synthesize mTableView,fListArray,shopsId,classId;

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    
    for (UIView *subView in [[searchBar.subviews objectAtIndex:0] subviews])
    {
        if([subView isKindOfClass:[UIButton class]]){
            [(UIButton*)subView setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    return YES;
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0)
{
    return YES;
}
#pragma mark  UISearchBar 响应事件
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [mTableView.header beginRefreshing];
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = bgColor;
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ShopsFL"] style:UIBarButtonItemStylePlain target:self action:@selector(rightAction1)];
    
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ShopsFLs"] style:UIBarButtonItemStylePlain target:self action:@selector(rightAction2)];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:item1,item2, nil];
    
    
    m_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 0, 100, 41)];
    m_searchBar.delegate = self;
    m_searchBar.backgroundColor = [UIColor clearColor];
    m_searchBar.placeholder = (@"搜索所有商品");
    m_searchBar.keyboardType =  UIKeyboardTypeDefault;
    [self.navigationItem setTitleView:m_searchBar];
    //    [m_searchBar becomeFirstResponder];
    for (UIView *view in m_searchBar.subviews) {//去除背景色
        
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, geHight, screenMySize.size.width, screenMySize.size.height-geHight)];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    __weak __typeof(self) weakSelf = self;
    
    mTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    mTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    

    mSidebar = [[ShopsSidebar alloc] initWithFrame:CGRectMake(0, 64, screenMySize.size.width, geHight)];
    mSidebar.delegate = self;
    mSidebar.selectedIndex = -1;
    [mSidebar setTitle:[NSArray arrayWithObjects:@"人气",@"销量",@"新品",@"价格", nil] setImage:[NSArray arrayWithObjects:@"ShopsRQ",@"ShopsXL",@"ShopsSP",@"ShopsJG", nil]  setSeclet:[NSArray arrayWithObjects:@"ShopsRQS",@"ShopsXLS",@"ShopsSPS",@"ShopsJG1",@"ShopsJG2", nil] setBOOL:YES];
    [self.view addSubview:mSidebar];
    
    
    if (classId == nil) {
        classId = @"0";
    }
    [mSidebar setSelectedSegmentIndex:0];
}

-(void)rightAction2
{
    
}

-(void)rightAction1
{
    JKSideSlipView *oneSl = (JKSideSlipView*)[[UIApplication sharedApplication].keyWindow viewWithTag:122];
    if (oneSl != nil) {
        [oneSl removeFromSuperview];
        oneSl = nil;
    }
    ShopsClassView *screenOne = [[ShopsClassView alloc] initWithFrame:CGRectMake(0, 0, SLIP_WIDTH, screenMySize.size.height)];
    screenOne.shopsId = shopsId;
    screenOne.delegate = self;
    //侧栏
    JKSideSlipView *_sideSlipView = [[JKSideSlipView alloc]initWithSender:self];
    _sideSlipView.backgroundColor = [UIColor clearColor];
    [_sideSlipView setContentView:screenOne];
    _sideSlipView.tag = 122;
    [[UIApplication sharedApplication].keyWindow addSubview:_sideSlipView];
    [_sideSlipView hide];
}

-(void)JKSshow:(NSString*)class1Id
{
    JKSideSlipView *oneSl = (JKSideSlipView*)[[UIApplication sharedApplication].keyWindow viewWithTag:122];
    if (oneSl != nil) {
        [oneSl show];
    }
    [mTableView.header beginRefreshing];
    classId = class1Id;
}


- (void)ShopsSidebar:(int)aType
{
    if (aType == 0) {
        orderBy = 0;
    }
    else if (aType == 1) {
        orderBy = 17;
    }
    else if (aType == 2) {
        orderBy = 16;
    }
    else if (aType == 3)
    {
        orderBy = mSidebar.goThreeIndex;
    }
    [mTableView.header beginRefreshing];
}
- (void)loadNewData
{
    pageForNumber = 1;
    [self upDateTableView];
}
- (void)loadMoreData
{
    pageForNumber++;
    [self upDateTableView];
}

-(void)upDateTableView
{
    if ((pageForNumber-1)*itemLabel <= [fListArray count]||pageForNumber ==1)
    {
        NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
        [postDic setObject:shopsId forKey:@"shopId"];
        [postDic setObject:classId forKey:@"searchShopCategoryId"];
        if (m_searchBar.text.length == 0)
            [postDic setObject:@"" forKey:@"searchKeyWord"];
        else
            [postDic setObject:m_searchBar.text forKey:@"searchKeyWord"];
        [postDic setObject:[NSNumber numberWithInt:pageForNumber] forKey:@"pageNumber"];
        [postDic setObject:[NSNumber numberWithInt:itemLabel] forKey:@"pageSize"];
        [postDic setObject:[NSNumber numberWithInt:orderBy] forKey:@"orderBy"];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            NSDictionary *ret = [SendService GetProductsByShopCategoryId:postDic];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"店铺商品列表 %@",ret);
                if (ret !=nil)
                {
                    if (pageForNumber == 1)
                    {
                        if (fListArray != nil)
                        {
                            [fListArray removeAllObjects];
                            fListArray = nil;
                        }
                        fListArray = [[NSMutableArray alloc] init];
                    }
                    for (NSDictionary *pic in [[ret objectForKey:@"Entity"] objectForKey:@"ProductList"])
                    {
                        [fListArray addObject:pic];
                    }
                    
                }
                if (pageForNumber ==1)
                    [mTableView.header endRefreshing];
                else
                    [mTableView.footer endRefreshing];
                [mTableView reloadData];
                
            });
        });
        
    }
    else
    {
        [mTableView.footer noticeNoMoreData];
        [mTableView reloadData];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return fListArray.count/2+fListArray.count%2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60+sizeHight+5;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"search";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
    }
//    cell.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    aTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    for (int i = 0; i < 2; i++)
    {
        if (indexPath.row*2+i >= fListArray.count) {
            return cell;
        }
        
        NSDictionary *dic = [fListArray objectAtIndex:indexPath.row*2+i];
        
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10+i*(screenMySize.size.width-10)/2,5, sizeHight,sizeHight)];
        [bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"DefaultPictureModel" ] objectForKey:@"ImageUrl"]]]];
        bgImageView.contentMode =  UIViewContentModeScaleAspectFit;
        bgImageView.backgroundColor  = [UIColor whiteColor];
        [cell.contentView addSubview:bgImageView];
        

        [cell.contentView addSubview:[self setFrame:CGRectMake(bgImageView.frame.origin.x, bgImageView.frame.origin.y+sizeHight, sizeHight, 40) setTitle:[NSString stringWithFormat:@"%@",[dic objectForKey:@"Name"]] setFont:labelSize setColor:[UIColor grayColor]]];

        
        [cell.contentView addSubview:[self setFrame:CGRectMake(bgImageView.frame.origin.x, bgImageView.frame.origin.y+sizeHight+40, sizeHight, 20) setTitle:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"ProductPrice"] objectForKey:@"Price"]] setFont:labelSize setColor:[UIColor redColor]]];
        
        UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgButton setFrame:CGRectMake(10+i*(screenMySize.size.width-10)/2,5, sizeHight,sizeHight+60)];
        [bgButton addTarget:self action:@selector(gotoAction:) forControlEvents:UIControlEventTouchUpInside];
        bgButton.tag =indexPath.row*2+i+1000;
        [cell.contentView addSubview:bgButton];
    }
    
    
    
    return cell;
}


-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(int)font setColor:(UIColor*)myColor
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:font];
    titleLabel.textColor = myColor;
    return titleLabel;
}

-(void)gotoAction:(id)sender
{
     int type = ((UIButton*)sender).tag -1000;
    GoodsDetailsViewController *details = [[GoodsDetailsViewController alloc] init];
    details.productId = [NSString stringWithFormat:@"%@",[[[fListArray objectAtIndex:type] objectForKey:@"ReviewOverviewModel"] objectForKey:@"ProductId"]];
    details.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:details animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
